package com.gcd.tempe;

import java.util.ArrayList;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gcd.tempe.util.JSON_Response;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class LihatBarangActivity extends Activity {
	
/** Called when the activity is first created. */

	private Integer currentCategoryId = null;
	private ArrayList<Integer> idcateglist = new ArrayList<Integer>();
	private JSONArray barangall;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lihat_barang);		
		setOtherViews();
		barangall = JSON_Response.getAllItems();
	}
	
	private void setOtherViews() {
		//set list kategori view
		setListCategory();
		
		//set listener tombol 'cari'
		setSearchButtonListeners();
		
		//set listener tombol 'refresh'
		setRefreshButtonListeners();
		
		//set konten pake barang-barang dari kategori x
		//setContentItemsBarang(JSON_Response.getItemsByCategory(currentCategoryId));
		setContentItemsBarang(barangall);
	}
	
	
	private void setListCategory() {
		//JSONArray daftarkategori = kategori;//JSON_Response.getJSONResponse(GET_ALL_KATEGORI);
		JSONArray daftarkategori = JSON_Response.getAllCategories();	
		String[] items = getKategoriBarangNames(daftarkategori);
		Spinner spinner = (Spinner) findViewById(R.id.choose_kategori);
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, items);
		
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		
		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				
				currentCategoryId = idcateglist.get(position);
				setContentItemsBarang(JSON_Response.getItemsByCategory(currentCategoryId));
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
	}
	
	private void setSearchButtonListeners() {
		Button button = (Button) findViewById(R.id.searchbutton);
		button.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				EditText Term = (EditText) findViewById(R.id.searchtext);
				String term = Term.getText().toString();
				Log.d("ancret", "term : " + term);
				
				setContentItemsBarang(JSON_Response.getItemsByTermAndCateg(term, currentCategoryId));
			}
		});
	}
	
	private void setRefreshButtonListeners() {
		Button button = (Button) findViewById(R.id.Refresh);
		button.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				System.gc();
				setOtherViews();
			}
		});
	}
	
	//return list of nama-kategori
	private String[] getKategoriBarangNames(JSONArray jsonArray) {
		ArrayList<String> temp = new ArrayList<String>();
		idcateglist.clear();
		
		try {
			
			//get default kategori id --> first id found
			if (jsonArray.length() > 0) {
//				currentCategoryId = jsonArray.getJSONObject(0).getInt("id");
				currentCategoryId = 2;
			}
			
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				temp.add(jsonObject.getString("nama"));
				idcateglist.add(jsonObject.getInt("id"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return temp.toArray(new String[temp.size()]);
	}
	
	//set isi tampilan barang di kategori yang sedang dipilih
	private void setContentItemsBarang(JSONArray jsonArray) {
		LinearLayout ll = (LinearLayout) findViewById(R.id.wrapperbarang);
		ll.removeAllViewsInLayout();
		
		try {
			for (int i = 0; i < jsonArray.length(); i++) {
				final JSONObject jsonObject = jsonArray.getJSONObject(i);				
				
				LinearLayout lytContainer = new LinearLayout(this);
				lytContainer.setOrientation(LinearLayout.VERTICAL);
				if (i % 2 == 1) {
					lytContainer.setBackgroundColor(Color.WHITE);
				} else {
					lytContainer.setBackgroundColor(Color.DKGRAY);
				}
				
				
				Drawable image = JSON_Response.ImageOperations(this, jsonObject.getString("path_gambar"),"image.jpg");
				ImageView iv = new ImageView(this);
				iv.setAdjustViewBounds(true);
				iv.setMaxHeight(50);
				iv.setMaxWidth(50);
				iv.setImageDrawable(image);
				iv.setPadding(0, 10, 0, 0);
				lytContainer.addView(iv);
				
				TextView t = new TextView(this);
				t.setText(jsonObject.getString("nama"));
				t.setGravity(Gravity.CENTER);
				t.setTypeface(null, Typeface.BOLD);
				if (i % 2 == 1) {
					t.setTextColor(Color.BLACK);
				} else {
					t.setTextColor(Color.WHITE);
				}
				lytContainer.addView(t);
				
				TextView t2 = new TextView(this);
				t2.setGravity(Gravity.CENTER);
				t2.setText("Jumlah produk yang tersedia : " + jsonObject.getString("jumlah"));
				if (i % 2 == 1) {
					t2.setTextColor(Color.BLACK);
				} else {
					t2.setTextColor(Color.WHITE);
				}
				t2.setPadding(0, 0, 0, 10);
				lytContainer.addView(t2);
				
				lytContainer.setOnClickListener(new OnClickListener() {
					
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						
						try {
							System.gc();
							
							Intent intent = new Intent(LihatBarangActivity.this, LihatItemBarangActivity.class);
							intent.putExtra("id", jsonObject.getInt("id"));
							intent.putExtra("kategori_id", jsonObject.getInt("kategori_id"));
							intent.putExtra("nama", jsonObject.getString("nama"));
					    	intent.putExtra("deskripsi", jsonObject.getString("deskripsi"));
					    	intent.putExtra("jumlah", jsonObject.getString("jumlah"));
					    	intent.putExtra("harga", jsonObject.getString("harga_satuan"));
					    	intent.putExtra("path_gambar", jsonObject.getString("path_gambar"));
					    	startActivity(intent);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
				
				ll.addView(lytContainer);
			}
		} catch (Exception e) {
			Log.d("ancret", e.toString());
			e.printStackTrace();
		}
	}
}